package com.example.common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.common.base.BaseActivity
import com.example.common.base.BaseEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviActivity<T:ViewDataBinding> :BaseActivity<T>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //注册EVentBus
        EventBus.getDefault().register(this)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event : BaseEvent){
        if (event != null && event.target==this::class.java.simpleName){
            handEvent(event)
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    override fun initData() {
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    override fun updateUI() {
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUIState()
            }
        }
    }


    open fun handEvent(event: BaseEvent){

    }

    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUIState(){

    }


}